package validators;

import it.polimi.authentication.ejb.usermanagement.*;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

@ManagedBean(name = "validateEmail")
@RequestScoped
public class ValidateEmail implements Validator {

        @EJB
        private UserMgr utenzaMgr;

        @Override
        public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {

                String email = (String) value;
                List<String> emailList = new ArrayList<String>();
                emailList = utenzaMgr.getAllEmails();

                if (email == null) {
                        throw new ValidatorException(generaMessaggio("may not be empty!", context));
                }

                if (emailList.contains(email)) {
                        throw new ValidatorException(generaMessaggio("Sei gia' registrato con questa mail", context));
                }
        }

        private FacesMessage generaMessaggio(String testoMessaggio, FacesContext context) {
                FacesMessage message = new FacesMessage();
                message.setSeverity(FacesMessage.SEVERITY_ERROR);
                message.setSummary(testoMessaggio);
                context.addMessage("userForm:dataNascita", message);
                return message;
        }
}
